﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using SARS.Biz;
using SARS.Biz.Facades;
using SARS.Entity;

namespace SARS.Course
{
    public partial class ViewStudentCourse : Page
    {
        private readonly ICourseBO _courseBO = new CourseBO();
        private readonly IProgramBO _programmeBO = new ProgramBO();
        private readonly ISessionBO _sessionBO = new SessionBO();
        private readonly IUserBO _userBO = new UserBO();
        private string course_id = string.Empty;
        private string program_id = string.Empty;

        private List<StudentCourseEntity> StudentCourseList
        {
            get { return (List<StudentCourseEntity>) Session["StudentCourseListSession"]; }
            set { Session["StudentCourseListSession"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                program_id = Request["pid"];
                course_id = Request["cid"];

                if (!string.IsNullOrEmpty(program_id) &&
                    !string.IsNullOrEmpty(course_id))
                {
                    StudentCourseList = RetrieveStudentCourseByCourseId(Convert.ToInt32(Request["cid"]));

                    lblProgram.Text = _programmeBO.RetrieveProgramById(Convert.ToInt32(program_id)).ProgramName;
                    lblCourse.Text = _courseBO.RetrieveCourseById(Convert.ToInt32(course_id)).CourseInfo;

                    grvStudents.DataSource = RetrieveStudentList();
                    grvStudents.DataBind();
                }
                else
                {
                    Response.Redirect("AssignStudentCourse.aspx");
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            List<StudentCourseEntity> studentCourseEntities = (from GridViewRow row in grvStudents.Rows
                let cbxIsAbsent = (CheckBox) row.FindControl("ckbIsAbsent")
                where cbxIsAbsent.Checked
                select new StudentCourseEntity
                {
                    CourseID = Convert.ToInt32(Request["cid"]),
                    StudentID = Convert.ToInt32(((HiddenField) row.FindControl("hdnStudentID")).Value),
                    RegisteredDate = DateTime.Now,
                    Status =
                        (CourseRegistryStatus)
                            Convert.ToInt32(((DropDownList) row.FindControl("ddlGrvStatuses")).SelectedValue)
                }).ToList();

            if (studentCourseEntities.Count > 0)
            {
                List<StudentCourseEntity> registeredStudentCourse = StudentCourseList;

                List<StudentCourseEntity> existingStudentCourse =
                    (studentCourseEntities.Where(
                        x =>
                            registeredStudentCourse.Any(
                                y => y.CourseID == x.CourseID && y.StudentID == x.StudentID))).ToList();

                List<StudentCourseEntity> newStudentCourse =
                    (studentCourseEntities.Where(
                        x =>
                            !registeredStudentCourse.Any(
                                y => y.CourseID == x.CourseID && y.StudentID == x.StudentID))).ToList();
                List<StudentCourseEntity> uncheckedStudentCourse =
                    (registeredStudentCourse.Where(
                        x =>
                            !studentCourseEntities.Any(y => y.CourseID == x.CourseID && y.StudentID == x.StudentID)))
                        .ToList();

                if (existingStudentCourse.Count > 0)
                {
                    foreach (StudentCourseEntity entity in existingStudentCourse)
                    {
                        _courseBO.UpdateStudentCourseById(entity);
                    }
                }
                if (newStudentCourse.Count > 0)
                {
                    _courseBO.AssignStudentToCourses(newStudentCourse);
                }
                if (uncheckedStudentCourse.Count > 0)
                {
                    foreach (StudentCourseEntity entity in uncheckedStudentCourse)
                    {
                        _courseBO.DeleteCourseStudentById(entity.CourseID, entity.StudentID);
                    }
                }

                Response.Redirect("AssignStudentCourse.aspx");
            }
        }

        protected void grvStudents_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //int x = Convert.ToInt32(e.Row.RowIndex);
                var chk = (CheckBox) e.Row.FindControl("ckbIsAbsent");
                var hdf = (HiddenField) e.Row.FindControl("hdnStudentID");
                var ddlStatus = (DropDownList) e.Row.FindControl("ddlGrvStatuses");
                StudentCourseEntity studentCourse =
                    StudentCourseList.FirstOrDefault(
                        x => x.CourseID == Convert.ToInt32(Request["cid"]) && x.StudentID == Convert.ToInt32(hdf.Value));
                //var studentCourse = StudentCourseList.FirstOrDefault(x => x.StudentID)

                chk.Checked = studentCourse != null;
                if (studentCourse != null) ddlStatus.SelectedValue = ((Int32) studentCourse.Status).ToString();
            }
        }

        private List<StudentCourseEntity> RetrieveStudentCourseByCourseId(int id)
        {
            return _courseBO.RetrieveStudentCourseByCourseId(id);
        }

        private List<UserEntity> RetrieveStudentList()
        {
            return _userBO.RetrieveUserByRoleId((int) RoleType.Student);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            List<StudentEntity> results = _userBO.SearchStudentByName(txtQuery.Text);

            grvStudents.DataSource = results;
            grvStudents.DataBind();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("AssignStudentCourse.aspx");
        }
    }
}